package com.zhuoyue.biz.core.api.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuoyue.biz.core.api.dao.DeviceDao;
import com.zhuoyue.biz.core.api.domain.DeviceDO;

import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.zhuoyue.biz.core.api.dao.JointControlRelationDao;
import com.zhuoyue.biz.core.api.domain.JointControlRelationDO;
import com.zhuoyue.biz.core.api.service.JointControlRelationService;
import com.zhuoyue.common.constant.ResultCode;
import com.zhuoyue.common.dto.BaseResultDTO;
import com.zhuoyue.common.dto.BatchResultDTO;

/**
 * @author wjming
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class JointControlRelationServiceImpl extends ServiceImpl<JointControlRelationDao, JointControlRelationDO> implements JointControlRelationService {

    private final JointControlRelationDao jointControlRelationDao;
    private final DeviceDao deviceDao;

    private static final String OD_0FBE_4030 = "4030";
    private static final String OD_0FAA_4010 = "4010";
    private static final String OD_0FAB_4011 = "4011";
    private static final String OD_0FAA = "0FAA";
    private static final String OD_0FAB = "0FAB";
    private static final String OD_0FBE = "0FBE";
    private static final String OD_ = "_";
    private static final int RELATION_MAX_12 = 12;
    private static final int RELATION_MAX_8 = 8;
    private static final String DEVICE_TYPE_08 = "08";
    private static final String DEVICE_TYPE_02 = "02";

    @Override
    public BaseResultDTO getJointControlRelationListByStartDeviceId(
            String gateWayId, String startDeviceMac, String startDeviceProductTypeStr, String type) {
        BatchResultDTO<JointControlRelationDO> result = new BatchResultDTO<JointControlRelationDO>();

        try {

            JointControlRelationDO jointObj = new JointControlRelationDO();
            if (!OD_0FBE_4030.equals(type)) {
                String startDeviceNum = "1";
                //Java String.contains()方法用法实例教程, 返回true，当且仅当此字符串包含指定的char值序列
                if (startDeviceProductTypeStr.contains(OD_)) {
                    startDeviceNum = startDeviceProductTypeStr.split("_")[1];
                    startDeviceProductTypeStr = startDeviceProductTypeStr.split("_")[0];
                } else {
                    startDeviceNum = "1";
                }
                jointObj.setGateWayId(gateWayId);
                jointObj.setStartDeviceMac(startDeviceMac);
                jointObj.setStartDeviceNum(startDeviceNum);
                jointObj.setProductType(startDeviceProductTypeStr);
            }

            List<JointControlRelationDO> list = new ArrayList<JointControlRelationDO>();
            //4010
            if (OD_0FAA_4010.equals(type)) {
                list = jointControlRelationDao
                        .selectJointControlRelationListByStartDeviceId4010(jointObj);
                if (CollectionUtils.isEmpty(list)) {
                    result.setSuccess(false);
                    result.setResultCode(ResultCode.NO_DATA);
                    result.setErrorDetail("该设备没有联控设备！");
                    return result;
                }
                //否则就是4011
            } else if (OD_0FAB_4011.equals(type)) {
                jointObj.setStartDeviceNum(startDeviceProductTypeStr);
                list = jointControlRelationDao
                        .selectJointControlRelationListByStartDeviceId4011(jointObj);
                if (CollectionUtils.isEmpty(list)) {
                    result.setSuccess(false);
                    result.setResultCode(ResultCode.NO_DATA);
                    result.setErrorDetail("该设备没有联控设备！");
                    return result;
                }
            } else if (OD_0FBE_4030.equals(type)) {
                jointObj.setStartDeviceMac(startDeviceMac);
                list = jointControlRelationDao
                        .selectJointControlRelationListByStartDeviceId4030(jointObj);
                if (CollectionUtils.isEmpty(list)) {
                    result.setSuccess(false);
                    result.setResultCode(ResultCode.NO_DATA);
                    result.setErrorDetail("该设备没有联控设备！");
                    return result;
                }
            }


            result.setSuccess(true);
            result.setResultCode(ResultCode.SUCCESS);
            result.setModule(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(
                    "JointControlRelationServiceImpl call getJointControlRelationListByStartDeviceId error ==== ",
                    e);
            result.setSuccess(false);
            result.setResultCode(ResultCode.SYS_ERROR);
            result.setErrorDetail("查询设备联控信息系统异常！");
        }
        return result;
    }

    /**
     * 添加联控
     *
     * @param relation
     * @param odIndex
     * @return
     */
    @Override
    public JointControlRelationDO addJointControlRelation(JointControlRelationDO relation, String odIndex) {
        Integer integer = jointControlRelationDao.selectCount(Wrappers.<JointControlRelationDO>lambdaQuery()
                .eq(JointControlRelationDO::getStartDeviceId, relation.getStartDeviceId())
                .eq(JointControlRelationDO::getStartDeviceMac, relation.getStartDeviceMac())
                .eq(JointControlRelationDO::getStartDeviceNum, relation.getStartDeviceNum())
                .eq(JointControlRelationDO::getEndDeviceId, relation.getEndDeviceId())
                .eq(JointControlRelationDO::getEndDeviceMac, relation.getEndDeviceMac())
                .eq(JointControlRelationDO::getEndDeviceNum, relation.getEndDeviceNum())
                .eq(JointControlRelationDO::getGateWayId, relation.getGateWayId()));
        if (integer > 0) {
            throw new ZyServerException(ErrorType.Service_Fail.getCode(), "联控关系已存在");
        }

        List<JointControlRelationDO> startDeviceId = jointControlRelationDao
                // 根据设备mac获得设备联控绑定的集合
                .selectRelationCount(relation.getStartDeviceMac(), relation.getGateWayId());
        if (startDeviceId == null) {
            throw new ZyServerException(ErrorType.INVALID_PARAMS.getCode(), "查询失败");
        }
        if (OD_0FAB.equals(odIndex) && startDeviceId.size() >= RELATION_MAX_12) {
            throw new ZyServerException(ErrorType.Service_Fail.getCode(), "该设备联控最多只能绑定12个");
        }
        if (OD_0FAA.equals(odIndex) && startDeviceId.size() >= RELATION_MAX_8) {
            throw new ZyServerException(ErrorType.Service_Fail.getCode(), "该设备联控最多只能绑定8个");
        }


        boolean isExiResult = false;
        boolean isdeviceNum = false;
        for (JointControlRelationDO jointControlRelationDO : startDeviceId) {
            if (jointControlRelationDO.getStartDeviceId().equals(
                    relation.getStartDeviceId())
                    && jointControlRelationDO.getEndDeviceId().equals(
                    relation.getEndDeviceId()) && relation.getGateWayId().equals(jointControlRelationDO.getGateWayId())) {
                isExiResult = true;
                break;
            }
        }
        if (isExiResult) {
            if (OD_0FBE.equals(odIndex)) {
                //去数据库取一下是否是0802
                List<DeviceDO> deviceDO = deviceDao.selectList(Wrappers.<DeviceDO>lambdaQuery()
                        .eq(DeviceDO::getZigbeeMac, relation.getStartDeviceMac()));
                //如果是0802说明是魔幻开关，接下来就要判断他是 “单击”还是“双击”
                if (DEVICE_TYPE_08.equals(deviceDO.get(0).getDeviceType()) && DEVICE_TYPE_02.equals(deviceDO.get(0).getProductType())) {
                    //判断是单击绑定或者是双击绑定
                    for (JointControlRelationDO jointControlRelationDO : startDeviceId) {
                        if (jointControlRelationDO.getStartDeviceId().equals(
                                relation.getStartDeviceId())
                                && jointControlRelationDO.getEndDeviceId().equals(
                                relation.getEndDeviceId())
                                && jointControlRelationDO.getStartDeviceNum().equals(
                                relation.getStartDeviceNum())
                                && jointControlRelationDO.getEndDeviceNum().equals(
                                relation.getEndDeviceNum())) {
                            isdeviceNum = true;
                            break;
                        }
                    }

                } else {
                    throw new ZyServerException(ErrorType.Service_Fail.getCode(), "设备联控已存在");
                }

            } else {
                throw new ZyServerException(ErrorType.Service_Fail.getCode(), "设备联控已存在");
            }
        }
        if (isdeviceNum) {
            throw new ZyServerException(ErrorType.Service_Fail.getCode(), "魔幻开关单击绑定事件已存在");
        }

        /**
         * 插入之前先获取一下index值用值1-8
         * */
        // 给个默认值1
        relation.setIndexId(1);
        int nine = 9;
        if (!startDeviceId.isEmpty()) {
            // 有值
            boolean isExit = false;
            for (int i = 1; i < nine; i++) {
                isExit = false;
                for (JointControlRelationDO forObj : startDeviceId) {
                    if (i == forObj.getIndexId()) {
                        isExit = true;
                        break;
                    }
                }
                if (!isExit) {
                    relation.setIndexId(i);
                    break;
                }
            }
        } else {
            // 空值
        }

        /**
         * 插入设备
         * */
        int count = jointControlRelationDao.insert(relation);
        System.out.println("输出的内容为" + count);
        if (count < 1) {
            throw new ZyServerException(ErrorType.Service_Fail.getCode(), "设备联控信息新增失败！");
        }
        JointControlRelationDO jointControlRelationDO = jointControlRelationDao.selectById(relation.getId());
        return jointControlRelationDO;
    }
}
